package com.tanjie.blackbean.web.support.encryption;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.GenericConverter;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.Set;

/**
 * @author: tanjie
 * @date: 2022-03-28
 **/
@Slf4j
@Component
public class EncryptionMessageConverter implements GenericConverter {

    @Override
    public Set<ConvertiblePair> getConvertibleTypes() {
        return Collections.singleton(new ConvertiblePair(String.class, EncryptionBean.class));
    }

    @Override
    public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
        if (source == null) {
            return null;
        }
        if (!(source instanceof String)) {
            return null;
        }
        String sourceString = (String) source;
        log.info("sourceString={}", sourceString);
        Class<?> type = targetType.getType();
        try {
            Object bean = JSONUtil.toBean(sourceString, type);
            log.info("bean={}", bean);
            return bean;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

}
